import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/8 18:09
 * @description 动态规划，dp[i][j]为以坐标(i,j)为右下角的正方形的边长
 * 确定边界，当matrix[i][j] = '1'时，i, 或 j == 0, dp[i][j] = 1;
 */
public class Solution {
    public static void main(String[] args) {

    }
    public int maximalSquare(char[][] matrix) {
        int maxSide = 0;
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return maxSide;
        }
        int rows = matrix.length, cols = matrix[0].length;
        int[][] dp = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == '1') {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        // （左边，上边，左上）的最小值 + 1，不懂可以画个图
                        dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                    }
                    maxSide = Math.max(maxSide, dp[i][j]);
                }
            }
        }
        return maxSide * maxSide;
    }
}
